#include "stdafx.h"
#include "xLog.h"

void xLog::PrintErrorCode(const char* linedesc, const char* filename, INT lineno, DWORD errcode)
{
    char* lpszBuffer = NULL;

    ::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        errcode,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPSTR)&lpszBuffer,
        0,
        NULL );

    char szErroBuffer[MAX_PATH] = {0};
    sprintf_s(szErroBuffer,
        "#Error{\n\n"
        "The following call failed at line %d in %s:\n"
        "%s\n\n"
        "Reason: %s"
        "\n}#Error\n",
        lineno,
        filename,
        linedesc,
        lpszBuffer);

    ::LocalFree(lpszBuffer);

#ifdef _WINDOWS
    char szModuleName[MAX_PATH] = {0};
    ::GetModuleFileNameA(NULL, szModuleName, MAX_PATH);
    ::MessageBoxA(NULL, szErroBuffer, szModuleName, MB_ICONWARNING | MB_OK | MB_TASKMODAL | MB_SETFOREGROUND);
#else
    DWORD dwRead = 0;
    ::WriteFile(::GetStdHandle(STD_ERROR_HANDLE), szErroBuffer, strlen(szErroBuffer), &dwRead, FALSE );
#endif
}